<?php
class Catalog_ItemController extends Zend_Controller_Action
{
protected $_auth;
protected $stdClass;
public $countScores;
public $countVotes;
public $input;
	public function preDispatch()
	{

	}
	public function init()
	{
     $this->_helper->getHelper('AjaxContext')
            ->addActionContext('validate','json')
            ->initContext();
    setlocale(LC_ALL, 'ru_RU.utf8');
	$this->_auth=Zend_Auth::getInstance()->getIdentity();

	}
	public function displayAction()
	{

	//-----Вывод-статьи---и-рейтинга----------------------------------------------------------
	$filters=array('id'=>array('HtmlEntities','StripTags','StringTrim'));
	$validators=array('id'=>array('NotEmpty','Digits'));
	
	$this->input=new Zend_Filter_Input($filters,$validators);
	$this->input->setData($this->getRequest()->getParams());
		if($this->input->isValid()){
			$q=Doctrine_Query::create()
				->from('Myblog_Model_Articles a')
				->leftJoin('a.Myblog_Model_Rating r')
				->select('a.article_id,a.article,a.category_name,a.author,a.link,a.page,a.title,a.created_dt,a.visibility,SUM(r.score),COUNT(r.id)')
				->where('a.article_id=?',$this->input->id);
				$result=$q->fetchArray();

	if(!empty($result[0])){

        $result[0]['created_dt'] = strftime('%d %B %Y',time($result[0]['created_dt']));
        $filter = new Zend_Filter_StripTags();
			$result[0]['title'] = $filter->filter($result[0]['title']);
			$this->view->item=$result[0];
			if($result[0]['SUM'] && $result[0]['COUNT']){
					$this->view->rating=$result[0]['SUM']/$result[0]['COUNT'];
			}else{
                    $this->view->rating=0;
			}
//-----Возращаем-5-похожих-статей---------------------------------	
		$q2=Doctrine_Query::create()			
			->from('Myblog_Model_Articles a')
			->where('a.category_name=?',$result[0]['category_name'])
			->whereNotIn('a.article_id',$result[0]['article_id'])
			->limit('5');
			$result3=$q2->fetchArray();
			if(!empty($result3))
			{
			for($i=0;$i<count($result3); $i++){
				$result3[$i]['title']=$filter->filter($result3[$i]['title']);
			}
			$this->view->title='Ссылки по теме:';
			$this->view->label=$result3;
			}
//--------Счетчик----------------------------------------------------				
		$cnt=Doctrine_Query::create()
			->from('Myblog_Model_Bestweekarticles b')
			->where('article_id=?',$this->input->id)
			->fetchArray();
			
		if(count($cnt)>=1)
		{
			if(!$_SERVER['REMOTE_ADDR']=='127.0.0.1')
			{
			$q3=Doctrine_Query::create()
				->update('Myblog_Model_Bestweekarticles')
				->set('count','count + 1')
				->where('article_id=?',$this->input->id)
				->execute();
			}
		}
		else{
				$nc=new Myblog_Model_Bestweekarticles;
				$nc->article_id=$this->input->id;
				$nc->date=date('Y-m-d');
				$nc->dayofweek=date('w');
				$nc->count=1;
				$nc->save();
			}
//-----Коментарии-----------------------------------------------------------			
				$q=Doctrine_Query::create()
					->from('Myblog_Model_Comments c')
					->where('c.visibility=?',1)
					->whereIn('c.article_id',$this->input->id)
					->orderBy('c.id ASC');
			$result2=$q->fetchArray();

				if($result2>=1)
				{
                    $this->view->commcount = count($result2);//Выводим кол-во комментариев
					for($i=0;$i<count($result2);$i++)
					{
						if($result2[$i]['role']==='guest')
						{
						$result2[$i]['role']='Гость';
						$result2[$i]['avatar']='images/avatars/noavatar92.png';
						}
						if($result2[$i]['role']==='user')
						{
						$result2[$i]['role']='';
						$u=Doctrine_Query::create()
							->from('Myblog_Model_Users u')
							->select('u.avatar')
							->where('u.username=?',$result2[$i]['name'])
							->fetchArray();
							if(!empty($u))
							{
							$result2[$i]['avatar']=$u[0]['avatar'];
							}
						}
						if($result2[$i]['role']==='admin')
						{
						$result2[$i]['role']='Админ';
						}
					}
				
				$bb=Zend_Markup::factory('Bbcode');
				$this->view->bb=$bb;
				$this->view->permit_comments=$result2;
				}
        Zend_Captcha_Word::$VN  = Zend_Captcha_Word::$CN = range(0,  9);
		if($this->_auth->status==='guest'){
			$comments=new Myblog_Form_Comments;
		}
		if($this->_auth->status==='user'){
			$comments=new Myblog_Form_UserComment;
			}
		if($this->_auth->status==='admin' || $this->_auth->status==='demo_admin'){
			
			$comments=new Myblog_Form_UserComment;
		}

		$comments->article_id->setValue($this->input->id);
		$this->view->comments=$comments;

		if($this->getRequest()->isPost() && $comments->isValid($this->_getAllParams()) ||
		$this->getRequest()->isXmlHttpRequest() && $comments->isValid($this->_getAllParams()))
		{

		$model=new Myblog_Model_Comments;

            $data=$comments->getValues();
			if($this->_auth->status==='user'){
			$model->fromArray($data);
			$model->name=$this->_auth->name;
			$model->email=$this->_auth->email;
			$model->role=$this->_auth->status;
            $model->author_id = $this->_auth->id;
			$model->save();
			}
			elseif($this->_auth->status==='guest'){
                    unset($data['author_id']);
					$model->fromArray($data);
					$model->role=$this->_auth->status;
					$model->save();
            }
            elseif($this->_auth->status === 'admin' || $this->_auth->status === 'demo_admin'){

                $model->fromArray($data);
                $model->name=$this->_auth->data[0]['username'];
                $model->email=$this->_auth->data[0]['email'];
                $model->role=$this->_auth->status;
                $model->author_id = $this->_auth->data[0]['id'];
                $model->save();
            }
		    $this->_helper->json(array('status'=>'XHR'));
		    if($this->getRequest()->isPost()){
				$this->_helper->getHelper('FlashMessenger')
						->addMessage('Ваш комментарий будет опубликован после проверки модератором');
				$this->_redirect('/catalog/success');
                }
        }
	}else{
			throw new Zend_Controller_Exception('Page is not found!', 404);
	     }
	}else{
			throw new Zend_Controller_Exception('Page is not found!', 404);
	     }
//------Breadcrumbs-----------------------------------------------

			$title=trim($result[0]['title'],'.');
			$title=mb_strtolower($title,'UTF-8');

			$catname=new Zend_Navigation_Page_Mvc(array(
                'label'         => $result[0]['category_name'],
                'module'        => 'catalog',
                'controller'    => 'item',
                'action'        => 'categoriesdisplay',
                'route'         => 'categories-display',
				'visible'       =>true,
				'params'        =>array('category'=>$result[0]['category_name']),
            ));
            $page=new Zend_Navigation_Page_Mvc(array(
                'label'         => $title,
                'module'        => 'catalog',
                'controller'    => 'item',
                'action'        => 'display',
                'route'         => 'catalog-display',
                'visible'       =>true,
                'params'        =>array('id'=>$result[0]['article_id']),
                //'active'        =>true
            ));
			$container=Zend_Registry::get('container');
			$breadcrumbs=$container->findByLabel('Статьи');
			$breadcrumbs->addPage($catname);
            $breadcrumbs=$container->findByLabel($result[0]['category_name']);
            $breadcrumbs->addPage($page);
	}

	public function validateAction()
	{

		if($this->_auth->status==='guest')
			{
			$form = new Myblog_Form_Comments;
			}
		if($this->_auth->status==='user' || $this->_auth->status==='admin' || $this->_auth->status==='admin')
		{
		$form = new Myblog_Form_UserComment;
		}
		
			$form->isValidPartial($this->_getAllParams());
			$data=$form->getValues();
			$msg = $form->getMessages();

            foreach($msg as $v=>$k){
                $this->view->$v = $k;
            }
	}

	public function ratingAction()
	{
		$ip=$this->getRequest()->getServer('REMOTE_ADDR');
		if($this->getRequest()->isXmlHttpRequest())
		{
		$this->_helper->getHelper('layout')->disableLayout();
		if($this->getRequest()->getPost('action')==='rating')
		{
		
		$rate = $this->getRequest()->getPost('rate');
		$artId = $this->getRequest()->getPost('artId');
		
			$q = Doctrine_Query::create()
				->from('Myblog_Model_Rating r')
				->select('INET_NTOA(r.ip),r.score,r.article_id')
				->where('r.article_id=?',$artId)
				->fetchArray();
			 
			if(!empty($q))
			{
				for($i=0; $i< count($q); $i++)
				{
					if($q[$i]['INET_NTOA'] ===$ip)
					{
						$this->_helper->json(array('repeat'=>true));
					}else{
									Myblog_Model_Rating::insertRating($ip,$artId,$rate);
							 }		
				}
			}else{
                    Myblog_Model_Rating::insertRating($ip,$artId,$rate);
			}
			$this->_helper->json(array('success'=>'success'));
			}
			if($this->getRequest()->isPost('articleid'))
			{
			$id=$this->getRequest()->getPost('articleid');
			$artId=Doctrine_Query::create()
				->from('Myblog_Model_Rating r')
				->select('INET_NTOA(r.ip),r.score,r.article_id')
				->where('r.article_id=?',$id)
				->fetchArray();

				if(!empty($artId) && count($artId)>=1)
				{
					$this->countVotes=0;
					$this->countScores=0;
					for($c=0; $c < count($artId);$c++)
					{
						$this->countVotes=$this->countVotes+1;	
					}
					for($s=0; $s < count($artId);$s++)
					{
						$this->countScores=$this->countScores+$artId[$s]['score'];
					}
					$countRepeat=0;
					$countNoRepeat=0;
					for($i=0; $i<count($artId);$i++)
					{
					
							if($artId[$i]['INET_NTOA']==$this->getRequest()->getServer('REMOTE_ADDR'))
							{
								$countRepeat+=1;
							}
							else{
									$countNoRepeat+=1;
									}	
					}
					if($countRepeat >=1){
									$this->_helper->json(array('article_score'=>$this->countScores,'article_votes'=>$this->countVotes,'repeat'=>true));
									}
						elseif($countRepeat===0){
									$this->_helper->json(array('article_score'=>$this->countScores,'article_votes'=>$this->countVotes,'repeat'=>false));
									}
					
				}else{
								$this->_helper->json(array('article_score'=>$this->countScores=0,'article_votes'=>$this->countVotes=0,'repeat'=>false));
						 }
			}
		}
	}
    //Render  category articles
	public function categoryItemsAction(){
        $filters=array('page'=>array('HtmlEntities','StripTags','StringTrim'),'category'=>array('HtmlEntities','StripTags','StringTrim'));
        $validators=array('page'=>array('Int'),'category'=>array());
        $input=new Zend_Filter_Input($filters,$validators);
        $input->setData($this->getRequest()->getParams());

        $q = Doctrine_Query::create()
            ->from('Myblog_Model_Articles a')
            ->leftJoin('a.Myblog_Model_Comments c')
            ->leftJoin('a.Myblog_Model_Bestweekarticles b')
            ->select('a.article_id,a.category_name,a.article,a.author,a.page,a.title,a.description,a.created_dt,a.img,COUNT(c.article_id) AS comments,COUNT(b.article_id) AS views')
            ->where('a.category_name=?',$input->category)
            ->addWhere('a.visibility=?','yes')
            ->groupby('a.article_id');

        $artCount = count($q->fetchArray());
        $perPage=5;
        $numPageLinks=5;
        $pager=new Doctrine_Pager($q,$input->page,$perPage);
        $result=$pager->execute(array(),Doctrine::HYDRATE_ARRAY);
        if(count($result)==0){
            $this->_helper->getHelper('FlashMessenger')
                ->addMessage('Записей не обнаружено');
            $this->_redirect('/message');
        }
        $pagerRange=new Doctrine_Pager_Range_Sliding(
            array('chunk'=>$numPageLinks),$pager);
        $pagerUrlBase=$this->view->url(array('category'=>$input->category),'categories-display',1) . "/{%page}";
        $pagerLayout=new Doctrine_Pager_Layout($pager,$pagerRange,$pagerUrlBase);
        $pagerLayout->setTemplate("<a class=btn href='{%url}'>{%page}</a>");

        $pagerLayout->setSelectedTemplate("<li class=active><a href='{%url}' >{%page}</a></li>");
        $pagerLayout->setSeparatorTemplate('');


        for($i=0;$i<count($result);$i++){
            $result[$i]['created_dt'] = strftime('%d %B %Y',time($result[$i]['created_dt']));
        }

        if($artCount > 5 || $input->page == $pager->getLastPage() && $artCount > 5){

            $this->view->items=$result;
            $this->view->pages ='<span class="btn" disabled="disabled" style="font-size:10px;margin-right:3px;">Всего статей: '.$pager->getNumResults().'</span><a class="btn" href="/categories/'.$input->category.'/'.$pager->getFirstPage().'"><i class="icon-fast-backward"></i></a>'.'<a class="btn" href="/categories/'.$input->category.'/'.$pager->getPreviousPage().'" title=Предыдущая ><i class="icon-step-backward"></i></a>'.$pagerLayout->display('',true).'<a class="btn" href="/categories/'.$input->category.'/'.$pager->getNextPage().'" title=Следующая><i class="icon-step-forward"></i></a>'.'<a class="btn" href="/categories/'.$input->category.'/'.$pager->getLastPage().'"><i class="icon-fast-forward"></i></a>'.'<span class="btn" disabled="disabled" style="font-size:10px;margin-left:3px;">Всего страниц: '.$pager->getLastPage().'</span>';
        }
        elseif($artCount <= 5)
        {
            $this->view->items=$result;
        }
    }
    public function channelAction(){


    }

	public function successAction()
	{
	if($this->_helper->getHelper('FlashMessenger')->getMessages()){
			$this->view->messages=$this->_helper
				->getHelper('FlashMessenger')->getMessages();
        $this->getResponse()->setHeader('Refresh','3; URL=/catalog/page');
				}else{
					$this->redirect('/');
					 }
	}
}
